import { defineStore } from "pinia";
import { USERINFO } from "@/type/resType/userResType";
import userRequest from "@/api/user";
import reminder from "@/utils/reminder";
import actionToken from "@/tools/actionToken";
import { reactive } from "vue";


// 使用组合式定义用户相关的仓库
const useUserStore = defineStore("user", () => {
    // 初始化一份用户信息数据
    const initUserInfo = (): USERINFO => ({
        token: actionToken.getToken(),
        nickName: "",
        name: "",
        id: 0,
        phoneName: "",
    })
    // 定义状态数据
    const state: USERINFO = reactive(initUserInfo())

    // 根据用户的token来获取用户的详细信息
    const getUserDetailInfo = async () => {
        try {
            let result = await userRequest.getUserDetailInfo();
            state.id = result.id;
            state.name = result.name;
            state.nickName = result.nickName;
            state.phoneName = result.phoneName;
        } catch (error: any) {
            reminder(error || "网络连接异常");
            return Promise.reject();
        }
    }
    // 退出登录
    const logoutHandler = async () => {
        try {
            await userRequest.logoutReqHandler();
            // 清除本地存储的token
            actionToken.removeToken();
            // 清空本地仓库中保存的用户信息
            Object.assign(state, initUserInfo());
        } catch (error: any) {
            reminder(error || "网络连接异常");
        }
    }
    return {
        state,
        getUserDetailInfo,
        logoutHandler
    }
});

export default useUserStore;